/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Database;

import GUI.LibraryTable;
import Records.RecordsMain;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Alexander
 */
public class UpdateLibraryImp {

    private static Thread threadUpdate = null;
    private static updateLibrary runUpdater = null;

    private static Thread threadLibraryStart = null;
    private static LibraryTable runLibraryStart = null;

    public static void startLibrary() {
        System.out.println("UpdateLibraryImp.startLibrary()");
        stopUpdate();
        runLibraryStart = new LibraryTable();
        threadLibraryStart = new Thread(runLibraryStart);
        //System.out.println("Starting Library thread: " + threadLibraryStart);
        threadLibraryStart.start();
        //System.out.println("Library successfully started.");
    }

    public static void updater() {
        System.out.println("UpdateLibraryImp.updater()");
        DefaultTableModel model = (DefaultTableModel) RecordsMain.getUI().userLibrary.getModel();
        if (model.getRowCount() == 0) {
            startLibrary();
        }
        runUpdater = new updateLibrary();
        threadUpdate = new Thread(runUpdater);
        System.out.println("Starting Update thread: " + threadUpdate);
        threadUpdate.start();
        System.out.println("Update successfully started.");
    }

    public static void stopUpdate() {
        System.out.println("UpdateLibraryImp.stopUpdate()");
        stopLibrary();
        //System.out.println("Stopping Update thread: " + threadUpdate);
        if (threadUpdate != null) {
            try {
                runUpdater.terminate();
                threadUpdate.join();
                //System.out.println("Update Thread successfully stopped.");
            } catch (InterruptedException ex) {
                Logger.getLogger(UpdateLibraryImp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void stopLibrary() {
                System.out.println("UpdateLibraryImp.stopLibrary()");

        //System.out.println("Stopping Library thread: " + threadLibraryStart);
        if (threadLibraryStart != null) {
            try {
                runLibraryStart.terminate();
                threadLibraryStart.join();
                System.out.println("Library Thread successfully stopped.");
            } catch (InterruptedException ex) {
                Logger.getLogger(UpdateLibraryImp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
